import * as vscode from 'vscode';
import { translate, letterToLowerCase, changeWord } from './utils/index';
const config = vscode.workspace.getConfiguration('vscodeTranslate');
let appKey = config.get('appKey') as string;
let appSecret = config.get('appSecret') as string;

if (!appKey || !appSecret) {
    appKey = '7ab91265f83e07b5';
    appSecret = 'FRAH9Om02OTPh8bTkgALs4PceCNej19g';
}


export function activate(context: vscode.ExtensionContext) {

    // 划词翻译
    vscode.languages.registerHoverProvider('*', {
        async provideHover(document) {
            const editor = vscode.window.activeTextEditor;

            if (!editor) {
                return;
            }

            const selection = editor.selection;
            const text = document.getText(selection);

            const res = await translate(changeWord(text), appKey, appSecret);

            const markdownString = new vscode.MarkdownString();

            markdownString.appendMarkdown(
                `#### 翻译 \n\n ${res.translation[0]} \n\n`
            );
            if (res.basic) {
                markdownString.appendMarkdown(
                    `**美** ${res.basic['us-phonetic']}~~~~~~**英** ${res.basic['uk-phonetic']}\n\n`
                );

                if (res.basic.explains) {
                    res.basic.explains.forEach((w) => {
                        markdownString.appendMarkdown(`${w} \n\n`);
                    });
                }
            }
            if (res.web) {
                markdownString.appendMarkdown('#### 网络释义 \n\n');
                res.web.forEach((w) => {
                    markdownString.appendMarkdown(
                        `**${w.key}:** ${String(w.value).toString()} \n\n`
                    );
                });
            }
            markdownString.supportHtml = true;
            markdownString.isTrusted = true;

            return new vscode.Hover(markdownString);
        }
    });

    // 中英互译
    const translateLetter = vscode.commands.registerCommand('vscode-translate.replace', async () => {
        let editor = vscode.window.activeTextEditor;

        if (!editor) {
            return;
        }
        let selection = editor.selection;

        // 选中的文本
        let text = editor.document.getText(selection);

        if (text.length) {
            const res = await translate(text, appKey, appSecret);

            editor.edit((builder) => {
                const result: string = res.translation[0];

                const letter: string = letterToLowerCase(result.split(''));
                const afterTranslate: string = letter.replace(/\s+\w{1}/g, (char: string) => {
                    return char.trim().toUpperCase();
                });

                // 替换选中文本
                builder.replace(selection, afterTranslate);
            });
        }
    });

    context.subscriptions.push(translateLetter);
}
